﻿using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class GateService_VailCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //string cde = CreateRandomCode(4);
            // CreateImage(cde);

            int _randomAngle = 40; //随机码的旋转角度
            int _fontSize = 17; //字体最大尺寸
            Color _backgroundColor = Color.White; //背景色
            string chars = string.Empty;
            //颜色列表，用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman", "MS-DOS", "Book Antiqua Italic", "Verdana Bold", "Bookman Old Style Bold", "Impact" };
            //验证码的字符集，去掉了一些容易混淆的字符 
            char[] character = { '1', '2', '3', '4', '5', '6', '8', '9', '0' };
            Random rnd = new Random();
            //生成验证码字符串 
            for (int i = 0; i < 5; i++)
            {
                chars += character[rnd.Next(character.Length)];
            }
            Session["vcdo"] = chars;
            Bitmap map = new Bitmap(65, 25); //创建图片背景
            Graphics graph = Graphics.FromImage(map);
            graph.SmoothingMode = SmoothingMode.AntiAlias;
            graph.Clear(_backgroundColor); //清除画面，填充背景

            Point dot = new Point(10, 10);
            //画噪线 
            PointF ulCorner = new PointF(rnd.Next(2), rnd.Next(25));
            PointF urCorner = new PointF(rnd.Next(65), rnd.Next(25));
            PointF llCorner = new PointF(rnd.Next(60, 75), rnd.Next(20, 25));
            PointF[] p = { ulCorner, urCorner, llCorner };
            Pen penxu = new Pen(color[rnd.Next(color.Length)], 1);
            penxu.DashStyle = DashStyle.Custom;
            penxu.DashPattern = new float[] { rnd.Next(10, 15), rnd.Next(1, 3) };
            graph.DrawCurve(penxu, p, 0.5F);
            //文字距中
            StringFormat format = new StringFormat(StringFormatFlags.NoClip);
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;


            //验证码旋转，防止机器识别
            for (int i = 0; i < chars.Length; i++)
            {
                Color _fontColor = color[rnd.Next(color.Length)];
                SolidBrush brush = new SolidBrush(_fontColor); //画笔
                string _fontFamily = font[rnd.Next(font.Length)];
                Font fontstyle = new Font(_fontFamily, rnd.Next(_fontSize - 3, _fontSize), FontStyle.Regular); //字体样式
                float angle = rnd.Next(-_randomAngle, _randomAngle); //转动的度数
                graph.TranslateTransform(dot.X, dot.Y); //移动光标到指定位置
                graph.RotateTransform(angle);
                graph.DrawString(chars[i].ToString(), fontstyle, brush, -2, 2, format);
                graph.RotateTransform(-angle); //转回去
                graph.TranslateTransform(2, -dot.Y); //移动光标到指定位置
            }

            //加防识别标记
            //string fnt_ht = font[rnd.Next(font.Length)];
            //Font ft_ht = new Font(fnt_ht, 7);
            //graph.DrawString("810h", ft_ht, new SolidBrush(Color.Gold), -70, 1);

            //将验证码图片写入内存流，并将其以"image/Png" 格式输出 
            MemoryStream ms = new MemoryStream();
            try
            {
                map.Save(ms, ImageFormat.Png);
                Response.ClearContent();
                Response.ContentType = "image/Png";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                //显式释放资源 
                map.Dispose();
                graph.Dispose();
            }
            
            
            
        }
    }
    
    private string CreateRandomCode(int codeCount)
    {
        string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
        string[] allCharArray = allChar.Split(',');
        string randomCode = "";
        int temp = -1;

        Random rand = new Random();
        for (int i = 0; i < codeCount; i++)
        {
            if (temp != -1)
            {
                rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
            }
            int t = rand.Next(35);
            if (temp == t)
            {
                return CreateRandomCode(codeCount);
            }
            temp = t;
            randomCode += allCharArray[t];
        }
       
        return randomCode;
    }


    private void CreateImage(string checkCode)
    {
        int iwidth = (int)(checkCode.Length * 11.5);
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 22);
        Graphics g = Graphics.FromImage(image);
        Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);
        Brush b = new System.Drawing.SolidBrush(Color.White);
        //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
        g.Clear(Color.Gray);
        g.DrawString(checkCode, f, b, 3, 3);

        Pen blackPen = new Pen(Color.Black, 0);
        Random rand = new Random();
        for (int i = 0; i < 2; i++)
        {
            int y = rand.Next(image.Height);
            g.DrawLine(blackPen, 0, y, image.Width, y);
        }

        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
       
       
        Session["vcdo"] = checkCode.ToString();


        Response.ClearContent();
       Response.ContentType = "image/Jpeg";
       Response.BinaryWrite(ms.ToArray());
       Response.End();
       g.Dispose();
       image.Dispose();
     
    }

  
}